//
//  ZLCalendarSaleDetailVC.swift
//  TestDemo
//
//  Created by ayin on 2019/5/29.
//  Copyright © 2019 aYin. All rights reserved.
//  日历-发售详情

import UIKit

let ZLCalendarNotifiSubTableCanMoveKey = NSNotification.Name.init(rawValue: "SubTableViewCanMove")
let ZLCalendarNotifiContentScrollCanMoveKey = NSNotification.Name.init(rawValue: "ContentScrollViewCanMove")
let ZLCalendarNotifiContentScrollOffsetYKey = NSNotification.Name.init(rawValue: "ContentScrollOffsetY")

let ZLCalendarNotifiContentScrollOnly = NSNotification.Name.init(rawValue: "ContentScrollOnly")

class ZLCalendarSaleDetailVC: UIViewController {
    //MARK: - 声明属性
    //nav
    fileprivate lazy var navBar : SaleDetailsNaviBar = {
        let navBar = SaleDetailsNaviBar()
        navBar.delegate = self
        return navBar
    }()
    
    //内容view
    lazy var contentScrollView: ZLCalendarSaleDetailScrollView = {
        let scrollView = ZLCalendarSaleDetailScrollView(frame: .zero)
        scrollView.backgroundColor = UIColor.white
        scrollView.bounces = false
        scrollView.showsVerticalScrollIndicator = false
        return scrollView
    }()
    
    //商品信息view
    lazy var headerView: ZLCalendarSaleDetailHeaderView = {
        let view = ZLCalendarSaleDetailHeaderView()
        view.delegate = self
        return view
    }()
    
    //城市选择view
    lazy var cityFilterView: CalendarTopFilterView = {
        let view = CalendarTopFilterView()
        view.delegate = self
        return view
    }()
    
    //列表view
    lazy var subTableView : UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 130
        tableView.estimatedSectionFooterHeight = 0
        tableView.estimatedSectionHeaderHeight = 44.up
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.backgroundColor = UIColor.white
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(ZLCalendarSaleDetailCell.self, forCellReuseIdentifier: "ZLCalendarSaleDetailCell")
        tableView.register(ZLCalendarSaleDetailSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: ZLCalendarSaleDetailSectionHeaderView.reuseId())
        return tableView
    }()
    
    // 球鞋收藏页面
//    lazy var storeShoeView: CalendarStoreView = {
//        let view = CalendarStoreView.init(frame: CGRect(x: screenWidth, y: 0, width: screenWidth, height: screenHeight))
//        return view
//    }()
    
    var tableCanMove: Bool = false
    var headerY: CGFloat = 0
    let sectionKeys: [String] = ["线上","北京","上海"]
    let cityList: [CTopFilterModel] = [CTopFilterModel(title: "线上"),CTopFilterModel(title: "北京"),CTopFilterModel(title: "上海")]
    
    var curCityIndex: Int = 0
    
    //MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        addNotifiObserver()
        setupNav()
        setupUI()

//        self.subTableView.contentSize = CGSize(width: screenWidth, height: screenHeight + 10)
        self.subTableView.addObserverBlock(forKeyPath: "contentSize") { [weak self] (ll, lll , llll) in
            guard let weakSelf = self else {return}
            let contentSize = weakSelf.subTableView.contentSize
            if contentSize.height <= screenHeight - 40.up - statusBarAndNavigationBarHeight {
                NotificationCenter.default.post(name: ZLCalendarNotifiContentScrollOnly, object: nil)
            }
            print("contentSize:\(contentSize)")
        }
    }
    
    
    deinit {
        removeNotifiObserver()
    }
    
    //MARK: - 搭建UI
    func setupNav() {
//        self.shouldHiddenNavigationBar = true
        view.addSubview(navBar)
        
        navBar.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(statusBarAndNavigationBarHeight)
        }
    }
    
    func setupUI() {
        if #available(iOS 11, *) {
            self.contentScrollView.contentInsetAdjustmentBehavior = .never
            self.subTableView.contentInsetAdjustmentBehavior = .never;
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(contentScrollView)
        contentScrollView.addSubview(headerView)
        contentScrollView.addSubview(cityFilterView)
        contentScrollView.addSubview(subTableView)
        
        contentScrollView.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview()
            make.width.equalTo(screenWidth)
            make.height.equalTo(screenHeight)
        }
        
        headerView.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview()
            make.width.equalTo(screenWidth)
            make.height.equalTo(210.up + statusBarAndNavigationBarHeight)
        }
        
        cityFilterView.snp.makeConstraints { (make) in
            make.left.width.equalToSuperview()
            make.top.equalTo(headerView.snp.bottom)
            make.height.equalTo(40.up)
        }
        
        subTableView.snp.makeConstraints { (make) in
            make.left.width.bottom.equalToSuperview()
            make.top.equalTo(cityFilterView.snp.bottom)
            make.height.equalTo(screenHeight - 40.up - statusBarAndNavigationBarHeight)
        }
        
        headerView.refreshDatas()
        cityFilterView.refreshDatas(cityList)
    }
}

extension ZLCalendarSaleDetailVC {
    //MARK: - 事件
    //通知后事件
    //添加通知监听者
    func addNotifiObserver() {
        NotificationCenter.default.addObserver(self, selector: #selector(tableViewCanMove(notification:)), name: ZLCalendarNotifiSubTableCanMoveKey, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(contentScrollOffsetY(notification:)), name: ZLCalendarNotifiContentScrollOffsetYKey, object: nil)
    }
    
    //移除通知
    func removeNotifiObserver() {
        NotificationCenter.default.removeObserver(self)
    }
    
    //接收到表可以滑动事件
    @objc func tableViewCanMove(notification: NSNotification) {
        tableCanMove = true
    }
    
    //接收到scrollview滑动事件
    @objc func contentScrollOffsetY(notification: NSNotification) {
        if let info = notification.userInfo, let offsetY = info["offsetY"] as? CGFloat {
            //nav透明度处理
            var alpha: CGFloat = 0
            if offsetY > 0 {
                alpha = offsetY / 251.up
            }else {
                alpha = 0
            }
            navBar.updateAlpha(alpha: alpha)
        }
    }
}

extension ZLCalendarSaleDetailVC: SaleDetailsNaviBarDelegate {
    //MARK: - 代理
    //MARK: NaviBarDelegate
    func backBtnActionClicked() {
        self.navigationController?.popViewController(animated: true)
    }
    
    func guideBtnActionClicked() {
        
    }
    
    func moreBtnActionClicked() {
        
    }
}

extension ZLCalendarSaleDetailVC: ZLCalendarSaleDetailHeaderViewDelegate, CalendarTopFilterViewDelegate {
    //MARK: HeaderViewDelegate
    //商品信息点击事件代理
    func productInfoViewTapAction(dataModel: Any) {
        print("商品信息点击事件代理")
    }
    
    //收藏事件代理
    func collectionAction(sender: UIButton, dataModel: Any) {
        sender.isSelected = !sender.isSelected
        print("收藏事件代理")
    }
    
    //商品图片浏览事件代理
    func subProductImgViewTapAction(imgView: UIImageView, index: Int) {
        print("商品图片浏览事件代理")
    }
    
    //MARK: CityFilterViewDelegate
    //segment各item点击回调
    func cTopFilterSelectedData(_ data:CTopFilterModel, indexPath:IndexPath) {
        print("城市切换事件代理")
        self.curCityIndex = indexPath.row
        for (index,value) in self.sectionKeys.enumerated().reversed() {
            if value == data.title {
                self.tableCanMove = true
                self.subTableView.scrollToRow(at: IndexPath(row: 0, section: index), at: .top, animated: true)
            }
        }
    }
}

extension ZLCalendarSaleDetailVC: UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource, ZLCalendarSaleDetailCellDelegate {
    //MARK: ScrollViewDelegate
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !tableCanMove {
            scrollView.contentOffset = .zero
        }
        
        let offY = scrollView.contentOffset.y
        if offY <= 0 {
            NotificationCenter.default.post(name: ZLCalendarNotifiContentScrollCanMoveKey, object: nil)
            tableCanMove = false
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //滑动表格停留时让城市也滑动到对应标题位置
//        if scrollView is UITableView,
//            let curVisibleIndexPaths = self.subTableView.indexPathsForVisibleRows,
//            let firstIndexPath = curVisibleIndexPaths.first {
//            let sectionkey = self.sectionKeys[firstIndexPath.section]
//            for (index,value) in self.cityList.enumerated().reversed() {
//                if value.title == sectionkey {
//                    self.cityFilterView.refreshScrollToIndexPath(IndexPath(row: index, section: 0))
//                }
//            }
//        }
        
        let curCityStr = self.cityList[self.curCityIndex].title
        if scrollView is UITableView,
            let curVisibleIndexPaths = self.subTableView.indexPathsForVisibleRows {
            for indexPath in curVisibleIndexPaths {
                let sectionkey = self.sectionKeys[indexPath.section]
                print("sectionkey---------------------\(sectionkey)")
                if sectionkey != curCityStr {
                    let index: Int = self.cityList.firstIndex(where: {$0.title == sectionkey})!
                    self.cityFilterView.refreshScrollToIndexPath(IndexPath(row: index, section: 0))
                    self.curCityIndex = index
                    return
                }
            }
        }
    }
    
    //MARK: TableViewDelegate
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionKeys.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ZLCalendarSaleDetailCell", for: indexPath) as! ZLCalendarSaleDetailCell
        cell.delegate = self
        cell.refreshDatas()
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44.up
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: ZLCalendarSaleDetailSectionHeaderView.reuseId()) as! ZLCalendarSaleDetailSectionHeaderView
        headerView.refreshDatas(title: self.sectionKeys[section])
        return headerView
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
    }
    
    //MARK: CellDelegate
    //点击头像事件代理
    func avatorClickAction(dataModel: Any) {
        print("点击头像事件代理")
    }
    
    //点击抽签/提醒按钮事件代理
    func drawLotsAction(sender: UIButton, dataModel: Any) {
        print("点击抽签/提醒按钮事件代理")
    }
    
    //点击交流箭头按钮事件代理
    func exchangeAction(sender: UIButton, dataModel: Any) {
        print("点击交流箭头按钮事件代理")
    }
}
